﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlackBird.Models;
using System.Net;
using System.IO;
using BlackBird.DataAccess;
using System.Web.UI;
using BlackBird.ControllerHelpers;

namespace BlackBird.Controllers
{
	public partial class FileUploadController : Controller
    {
        //
        // GET: /FileUpload/

		public virtual ActionResult Index()
        {
            return View();
        }


		/// <summary>
		/// 作为一个上传文件公共的方法
		/// 返回上传文件对话框
		/// </summary>
		/// <param name="type">类型</param>
		/// <param name="ParentId">parent id</param>
		/// <returns></returns>
		[HttpGet]
		[OutputCache(Location = OutputCacheLocation.None)]
		public virtual ActionResult UploadFilePartialView(SupportTypes type,string ParentId = "")
		{
			UploadFile uF = new UploadFile()
			{
				parentId = ParentId,
				type = type
			};

			return PartialView(MVC.Shared.Views.Util.UploadFile, uF);
		}

		[HttpPost]
		public virtual ActionResult UploadFiles(UploadFile info)
		{
			//var bijiadan = MockupDataStore.GetBiJiaDan(info.parentId);

			if (Request.Files.Count > 1)
				throw new NotSupportedException("Check Function FileUploadController.UploadFiles");

			object retObj = null;

			foreach (string file in Request.Files)
			{
				HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
				if (hpf.ContentLength == 0)
					continue;

				var savedFilePath = FileUploadHelper.SaveUploadFile(hpf,info.type);

				var currentUser = AccountHelper.GetCurrentUser(this);

				//Insert Fu Jian Info to fujian table.
				int fujianID = FuJianDataAccess.SaveFuJianItemToDB(Path.GetFileName(hpf.FileName), savedFilePath, hpf.ContentType, currentUser.idUser);

				//Update fujian parent table info.        
				retObj = FuJianDataAccess.UpdateInfoToParent(info, Path.GetFileNameWithoutExtension(hpf.FileName), fujianID, currentUser);

			}

			//if (bijiadan != null)
			//{
			//    MockupDataStore.UpdateBiJiaDan(bijiadan);
			//}

			//return Json(retObj, JsonRequestBehavior.AllowGet);
			return new HttpStatusCodeResult((int)HttpStatusCode.OK);
		}


		[HttpGet]
		public virtual ActionResult Download(string id)
		{
			var fileinfo = FuJianDataAccess.GetFuJianInfoByID(int.Parse(id));
			if (fileinfo == null)
				throw new FileNotFoundException("Download the expected file failed");

			return File(fileinfo.Path, fileinfo.MineType, fileinfo.Name);
		}


    }
}
